<?php


namespace App\Repositories;


use App\Exceptions\BasicException;
use Illuminate\Support\Facades\DB;

class MicrophoneRepository
{
    public function update($params = [])
    {
        if (!isset($params['is_open']) || !isset($params['is_all_room'])) {
            return false;
        }
        if ($params['is_open'] == 0) {//不开启这个功能
            $isAllRoomData = [
                'status' => 1,
                'value'  => 0,
            ];
            $roomData = [
                'status' => 1,
            ];
        } else {
            if ($params['is_all_room'] == 1) {//全部房间
                $isAllRoomData = [
                    'status' => 0,
                    'value'  => 1,
                ];
                $roomData = [
                    'status' => 1,
                ];
            } else {
                $isAllRoomData = [
                    'status' => 0,
                    'value'  => 0,
                ];
                $arrRoomIds = explode(',', $params['room_ids']);
                $arrRoomIds = array_unique($arrRoomIds);
                $allRoom = app('model_user_room')->get(['room_id'])->toArray();
                $allRoom = array_column($allRoom, 'room_id');
                foreach ($arrRoomIds as $k => $v) {
                    if ($v == "") {
                        unset($arrRoomIds[$k]);
                    }
                }
                foreach ($arrRoomIds as $v) {
                    if (!in_array($v, $allRoom)) {
                        throw new BasicException(10001, 'room_id:' . $v . '不存在！！！');
                    }
                }

                $params['room_ids'] = implode(',', $arrRoomIds);
                $roomData = [
                    'status' => 0,
                    'value'  => $params['room_ids'],
                ];
            }
        }

        DB::beginTransaction();
        try {
            app('repo_config')->saveConfig(["key" => 'NO_MONEY_OPEN'], ['value' => $params['is_open']]);
            app('repo_config')->saveConfig(["key" => 'NO_MONEY_ALL_ROOM'], $isAllRoomData);
            app('repo_config')->saveConfig(["key" => 'NO_MONEY_ROOM_CODES'], $roomData);
            DB::commit();
        } catch (\Exception $e) {
            throw new BasicException(0, $e->getMessage());
        }
        return true;
    }
}